var routes = exports;

var db   = require(".././database");
var util = require("util");

routes.index = function(req, res){
    if (req.session.username){
        res.render('index', {
            title: "Midgard",
            name: req.session.firstname + " " + req.session.lastname
        });
    } else {
        res.redirect("/login");
    }
};

routes.login = function(req,res){
    if (!req.session.username) {
        res.render('login', {title:"Login"})
    } else {
        res.redirect("/");
    }
}

routes.loginDo = function(req,res){
    if (!req.session.username){
        var data = req.body;
        //var userData = data.user;
        //console.log("Logging in with: "+util.inspect(data));
        //console.log("Username:" + data.user.name);
        db.getUser(data, function(err, user) {
            sessions.push(req.session);
            if(user) {
                req.session.user        = user;
                req.session.username    = user.username;
                req.session.password    = user.password;
                req.session.firstname   = user.firstname;
                req.session.lastname    = user.lastname;
                res.redirect("/");
            } else {
                res.redirect("/login");
            }
        });
    } else {
        res.redirect("/login");
    }
}

routes.logout = function(req,res){
    if (req.session.username) {
        req.session.destroy();
    }
    res.redirect("/login");
}

routes.newIdea = function(req, res){
    if (req.session.username){
        res.render('newidea', {title:"New Idea"});
    } else {
        res.redirect("/login");
    }
};

routes.saveCookie = function(req,res){;
    var data = req.body;
    res.cookie('theme', data['themechanger'], { maxAge: 15552000000 });
    res.redirect('back');
    console.log("Theme changed:" + data['themechanger']);
};